package controller

import (
	"net/http"
	"strconv"

	"github.com/example/video_backend/internal/service"
	"github.com/example/video_backend/pkg/logger"
	"github.com/gin-gonic/gin"
)

// CategoryController 分类控制器
// 处理与视频分类相关的HTTP请求

type CategoryController struct {
	categoryService service.CategoryService
}

// NewCategoryController 创建分类控制器实例
func NewCategoryController(categoryService service.CategoryService) *CategoryController {
	return &CategoryController{
		categoryService: categoryService,
	}
}

// CreateCategoryRequest 创建分类请求参数
type CreateCategoryRequest struct {
	Name        string `json:"name" binding:"required,min=2,max=50"`
	Description string `json:"description" binding:"max=255"`
}

// UpdateCategoryRequest 更新分类请求参数
type UpdateCategoryRequest struct {
	Name        string `json:"name" binding:"omitempty,min=2,max=50"`
	Description string `json:"description" binding:"omitempty,max=255"`
}

// CreateCategory 创建新分类
// @Summary 创建新分类
// @Description 创建新的视频分类
// @Tags 分类
// @Accept json
// @Produce json
// @Param request body CreateCategoryRequest true "创建分类请求参数"
// @Success 200 {object} Response{data=model.Category}
// @Router /api/v1/categories [post]
func (c *CategoryController) CreateCategory(ctx *gin.Context) {
	var req CreateCategoryRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		logger.Error("Create category request binding error: " + err.Error())
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: err.Error()})
		return
	}

	// 从上下文中获取用户ID和是否为管理员
	_, exists := ctx.Get("userID")
	isAdmin, adminExists := ctx.Get("isAdmin")
	if !exists || !adminExists || !isAdmin.(bool) {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "需要管理员权限"})
		return
	}

	category, err := c.categoryService.CreateCategory(ctx, req.Name, req.Description, 0)
	if err != nil {
		logger.Error("Create category error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "创建成功", Data: category})
}

// GetAllCategories 获取所有分类
// @Summary 获取所有分类
// @Description 获取系统中所有视频分类列表
// @Tags 分类
// @Accept json
// @Produce json
// @Success 200 {object} Response{data=[]model.Category}
// @Router /api/v1/categories [get]
func (c *CategoryController) GetAllCategories(ctx *gin.Context) {
	categories, err := c.categoryService.GetAllCategories(ctx)
	if err != nil {
		logger.Error("Get categories error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "获取成功", Data: categories})
}

// GetCategoryByID 根据ID获取分类
// @Summary 根据ID获取分类
// @Description 根据ID获取指定视频分类的详细信息
// @Tags 分类
// @Accept json
// @Produce json
// @Param id path int true "分类ID"
// @Success 200 {object} Response{data=model.Category}
// @Router /api/v1/categories/{id} [get]
func (c *CategoryController) GetCategoryByID(ctx *gin.Context) {
	// 获取分类ID
	categoryID, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: "无效的分类ID"})
		return
	}

	category, err := c.categoryService.GetCategoryByID(ctx, uint(categoryID))
	if err != nil {
		logger.Error("Get category by ID error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	if category == nil {
		ctx.JSON(http.StatusNotFound, Response{Code: 404, Message: "分类不存在"})
		return
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "获取成功", Data: category})
}

// UpdateCategory 更新分类
// @Summary 更新分类
// @Description 更新指定ID的视频分类信息
// @Tags 分类
// @Accept json
// @Produce json
// @Param id path int true "分类ID"
// @Param request body UpdateCategoryRequest true "更新分类请求参数"
// @Success 200 {object} Response{data=model.Category}
// @Router /api/v1/categories/{id} [put]
func (c *CategoryController) UpdateCategory(ctx *gin.Context) {
	// 获取分类ID
	categoryID, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: "无效的分类ID"})
		return
	}

	// 绑定请求参数
	var req UpdateCategoryRequest
	if err := ctx.ShouldBindJSON(&req); err != nil {
		logger.Error("Update category request binding error: " + err.Error())
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: err.Error()})
		return
	}

	// 从上下文中获取用户ID和是否为管理员
	_, exists := ctx.Get("userID")
	isAdmin, adminExists := ctx.Get("isAdmin")
	if !exists || !adminExists || !isAdmin.(bool) {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "需要管理员权限"})
		return
	}

	category, err := c.categoryService.UpdateCategory(ctx, uint(categoryID), req.Name, req.Description, 0)
	if err != nil {
		logger.Error("Update category error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	if category == nil {
		ctx.JSON(http.StatusNotFound, Response{Code: 404, Message: "分类不存在"})
		return
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "更新成功", Data: category})
}

// DeleteCategory 删除分类
// @Summary 删除分类
// @Description 删除指定ID的视频分类
// @Tags 分类
// @Accept json
// @Produce json
// @Param id path int true "分类ID"
// @Success 200 {object} Response
// @Router /api/v1/categories/{id} [delete]
func (c *CategoryController) DeleteCategory(ctx *gin.Context) {
	// 获取分类ID
	categoryID, err := strconv.ParseUint(ctx.Param("id"), 10, 64)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: "无效的分类ID"})
		return
	}

	// 从上下文中获取用户ID和是否为管理员
	_, exists := ctx.Get("userID")
	isAdmin, adminExists := ctx.Get("isAdmin")
	if !exists || !adminExists || !isAdmin.(bool) {
		ctx.JSON(http.StatusUnauthorized, Response{Code: 401, Message: "需要管理员权限"})
		return
	}

	// 检查分类是否存在视频
	hasVideos, err := c.categoryService.HasVideos(ctx, uint(categoryID))
	if err != nil {
		logger.Error("Check category has videos error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	if hasVideos {
		ctx.JSON(http.StatusBadRequest, Response{Code: 400, Message: "分类下存在视频，无法删除"})
		return
	}

	// 执行删除
	err = c.categoryService.DeleteCategory(ctx, uint(categoryID))
	if err != nil {
		logger.Error("Delete category error: " + err.Error())
		ctx.JSON(http.StatusInternalServerError, Response{Code: 500, Message: err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, Response{Code: 200, Message: "删除成功"})
}